#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <QDirIterator>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("GBK到UTF-8转换器");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_selectDirectoryButton_clicked()
{
    QString directory = QFileDialog::getExistingDirectory(this, tr("选择目录"),
                                                         ".",
                                                         QFileDialog::ShowDirsOnly
                                                         | QFileDialog::DontResolveSymlinks);

    if (!directory.isEmpty()) {
        selectedDirectory = directory;
        ui->directoryLineEdit->setText(directory);
        ui->convertButton->setEnabled(true);
    }
}

void MainWindow::on_convertButton_clicked()
{
    if (selectedDirectory.isEmpty()) {
        QMessageBox::warning(this, tr("警告"), tr("请先选择目录！"));
        return;
    }

    QDir dir(selectedDirectory);
    if (!dir.exists()) {
        QMessageBox::warning(this, tr("警告"), tr("所选目录不存在！"));
        return;
    }

    // 开始转换
    ui->statusBar->showMessage(tr("开始转换..."));
    convertDirectory(selectedDirectory);
    ui->statusBar->showMessage(tr("转换完成！"));
    QMessageBox::information(this, tr("成功"), tr("文件转换完成！"));
}

void MainWindow::convertDirectory(const QString &dirPath)
{
    QDirIterator it(dirPath, QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot,
                    QDirIterator::Subdirectories);

    while (it.hasNext()) {
        QString path = it.next();

        if (QFileInfo(path).isDir()) {
            convertDirectory(path);
        } else {
            // 只处理C++相关文件
            QString ext = QFileInfo(path).suffix().toLower();
            if (ext == "h" || ext == "cpp" || ext == "c" || ext == "hpp" || ext == "cc") {
                if (convertFile(path)) {
                    qDebug() << "转换成功: " << path;
                } else {
                    qDebug() << "转换失败: " << path;
                }
            }
        }
    }
}

bool MainWindow::convertFile(const QString &filePath)
{
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        return false;
    }

    QByteArray data = file.readAll();
    file.close();

    // 检查是否为GBK编码
    if (!isGBK(data)) {
        qDebug() << "文件不是GBK编码，跳过: " << filePath;
        return true; // 不是GBK编码，视为成功（不需要转换）
    }

    // 转换为UTF-8
    QString utf8Text = QString::fromLocal8Bit(data);
    if (utf8Text.size() == 0) {
        return true;// 不是GBK编码，视为成功（不需要转换）
    }

    // 写入文件（不带BOM）
    if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
        return false;
    }

    QTextStream out(&file);
    out.setCodec("UTF-8");
    out << utf8Text;
    file.close();

    return true;
}

// 简单检测是否为GBK编码（不完全可靠，但对大多数情况有效）
bool MainWindow::isGBK(const QByteArray &data)
{
    // 尝试检测BOM
    if (data.size() >= 3 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF) {
        return false; // UTF-8 with BOM
    }

    // 尝试用UTF-8解码，如果成功大概率是UTF-8
    QString utf8Test = QString::fromUtf8(data);
    if (utf8Test.toUtf8() == data) {
        return false; // 可能是UTF-8
    }

    // 默认为GBK
    return true;
}